<template>
  <div class="node_setting">
    <div class="setting_title">左连接</div>
    <div class="setting_item">
      <el-form :model="form" label-width="10px">
        <el-form-item>
          <el-input v-model="sourceTableName1" disabled placeholder="库表" style="width: 150px" />
          &nbsp;关联&nbsp;
          <el-input v-model="sourceTableName2" disabled placeholder="库表" style="width: 150px" />
        </el-form-item>
        <el-form-item v-for="(row, index) in form.relatedFieldsRows" :key="index">
          <el-select
            v-model="form.related_fields1[index]"
            placeholder="添加关联字段"
            size="large"
            style="width: 110px"
          >
            <el-option
              v-for="item in form.relatedFieldsOptions1"
              :key="item.name"
              :label="item.name"
              :value="item.name!"
            />
          </el-select>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <el-select
            v-model="form.related_fields2[index]"
            placeholder="添加关联字段"
            size="large"
            style="width: 110px"
          >
            <el-option
              v-for="item in form.relatedFieldsOptions2"
              :key="item.name"
              :label="item.name"
              :value="item.name!"
            />
          </el-select>
        </el-form-item>
        <!-- 新增行按钮 -->
        <el-button class="mt-10" type="primary" @click="addRow">新增行</el-button>
        <!-- 删除行按钮 -->
        <el-button class="mt-10" type="danger" @click="deleteRow">删除行</el-button>
      </el-form>
    </div>
    <el-button class="mt-4" type="primary" @click="sendData">保存</el-button>
  </div>
</template>
<script lang="ts">
export default { name: "RightJoinSetting" };
</script>
<script setup lang="ts">
import LogicFlow from "@logicflow/core";
import { MyLogicFlowPropertiesType } from "@/types/logic-flow";
import IndicatorManageAPI, {
  TableInfoParameter,
  FieldColumnsConfig,
  TableListParameter,
} from "@/api/strategy/strategy-index-database";
import { IgIndicatorJoinParameter, TableInfoConfig } from "@/api/strategy/strategyManage";
const props = defineProps<{
  lf?: LogicFlow;
  data: LogicFlow.NodeData | LogicFlow.EdgeData;
  parameter: TableListParameter;
}>();
const sourceTableName1 = ref<string>();
const sourceTableName2 = ref<string>();
const fieldColumnsConfigList1 = ref<FieldColumnsConfig[]>([]);
const fieldColumnsConfigList2 = ref<FieldColumnsConfig[]>([]);
const connectedData = ref<any[]>([]);
const tableInfoParameter = reactive<TableInfoParameter>({ id: 0, table: "" });
const igIndicatorJoinParameter = reactive<IgIndicatorJoinParameter>({});
const form = ref({
  relatedFieldsOptions1: [] as FieldColumnsConfig[],
  relatedFieldsOptions2: [] as FieldColumnsConfig[],
  relatedFieldsRows: [{}], // 初始化一行
  related_fields1: [] as string[],
  related_fields2: [] as string[],
});

// 请求表结构数据
async function handlerQueryRelated() {
  tableInfoParameter.id = props.parameter.id;
  tableInfoParameter.table = sourceTableName1.value;
  const response = await IndicatorManageAPI.TableInfo(tableInfoParameter);
  form.value.relatedFieldsOptions1 = response.columns!;
  if (sourceTableName2.value != "") {
    tableInfoParameter.table = sourceTableName2.value;
    const response2 = await IndicatorManageAPI.TableInfo(tableInfoParameter);
    form.value.relatedFieldsOptions2 = response2.columns!;
  }
}

// 提取的数据
const extractedData = computed(() => {
  console.log(connectedData.value);
  return connectedData.value.map((item) => {
    console.log("选中字段：：：" + item.tableData);
    return {
      sourceTableName: item.tableName,
      fieldColumnsConfig: item.tableData,
    };
  });
});
// 更新sourceTableName1和sourceTableName2
watch(extractedData, () => {
  sourceTableName1.value =
    extractedData.value.length > 0 ? extractedData.value[0].sourceTableName : "";
  fieldColumnsConfigList1.value =
    extractedData.value.length > 0 ? extractedData.value[0].fieldColumnsConfig : [];
  sourceTableName2.value =
    extractedData.value.length > 1 ? extractedData.value[1].sourceTableName : "";
  fieldColumnsConfigList2.value =
    extractedData.value.length > 1 ? extractedData.value[1].fieldColumnsConfig : [];
  if (sourceTableName1.value != "") {
    handlerQueryRelated();
  }
});
watch(
  () => props.data,
  (newVal) => {
    const incomingEdges = props.lf?.getNodeIncomingEdge(props.data.id);
    const sourceNodes = incomingEdges?.map((edge) => {
      return props.lf?.getNodeModelById(edge.sourceNodeId);
    });
    const dataForm = sourceNodes?.map((sourceNode) => {
      const sourceProperties = sourceNode?.getProperties();
      if (sourceNode?.type.includes("table_input")) {
        sourceProperties!.tableData = sourceProperties?.tableData.filter(
          (row: any) => row.isSelected
        );
      } else if (sourceNode?.type.includes("sql_input")) {
        sourceProperties!.tableName = sourceProperties?.tableName._value;
        sourceProperties!.tableData = sourceProperties?.tableData._value;
      }
      return sourceProperties;
    }) as any[];
    const {
      relatedFieldsOptions1,
      relatedFieldsOptions2,
      relatedFieldsRows, // 初始化一行
      related_fields1,
      related_fields2,
      connectedData: dataFromProps,
    } = newVal.properties as MyLogicFlowPropertiesType;
    form.value = {
      relatedFieldsOptions1: relatedFieldsOptions1 || [],
      relatedFieldsOptions2: relatedFieldsOptions2 || [],
      relatedFieldsRows: relatedFieldsRows || [], // 初始化一行
      related_fields1: related_fields1 || [],
      related_fields2: related_fields2 || [],
    };
    connectedData.value = dataForm || [];
    props.lf?.setProperties(newVal.id, {
      ...form.value,
    });
  },
  {
    immediate: true,
  }
);

// 定义自定义事件
const emits = defineEmits<{
  (event: "dataFetched", data: any): void;
}>();

// 新增行函数
const addRow = () => {
  form.value.relatedFieldsRows.push({});
  form.value.related_fields1.push("");
  form.value.related_fields2.push("");
};

// 删除行函数
const deleteRow = () => {
  if (form.value.relatedFieldsRows.length > 0) {
    form.value.relatedFieldsRows.pop();
    form.value.related_fields1.pop();
    form.value.related_fields2.pop();
  }
};

const sendData = () => {
  if (
    form.value.related_fields1.some((field) => field === "") ||
    form.value.related_fields2.some((field) => field === "")
  ) {
    ElMessage.warning("请选择关联字段");
  } else {
    const { related_fields1, related_fields2 } = form.value;
    let columnsList = [] as TableInfoConfig[];
    fieldColumnsConfigList1.value.map((item) => {
      columnsList.push({
        tableName: item.tableName,
        columnName: item.name,
        isUnique: false,
      });
    });
    fieldColumnsConfigList2.value.map((item) => {
      columnsList.push({
        tableName: item.tableName,
        columnName: item.name,
        isUnique: false,
      });
    });
    const newConnectedData = {
      propsDataId: props.data.id,
      relationData: {
        table1: sourceTableName1.value,
        table2: sourceTableName2.value,
        column1: related_fields1,
        column2: related_fields2,
        isNotNull: true,
        length: related_fields1.length,
      },
      tables: [sourceTableName1.value, sourceTableName2.value],
      columns: columnsList,
      joinType: ["LEFT JOIN"],
    };
    if (props.lf && props.data.id) {
      props.lf.setProperties(props.data.id, {
        ...form.value,
        joinConnectedData: newConnectedData,
      });
    } else {
      console.log("无法更新节点属性，props.lf 或 props.data.id 为空");
    }
    ElMessage.success("数据已保存"); // 提示用户选择数据
  }
};
</script>
<style lang="scss" scoped>
.setting-title {
  justify-content: center;
  padding: 10px 0;
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: bold;
  text-align: center;
  border-bottom: 1px solid #e9e9e9;
}

.setting-item {
  .setting-item-title {
    padding: 10px 0;
    margin-bottom: 10px;
    font-size: 14px;
    font-weight: bold;
    border-bottom: 1px solid #e9e9e9;
  }
}
</style>
